package com.heima.admin.gateway.filters;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * @author Macrydy
 * @date 2020/11/8
 */
@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断当前的请求是否为登录，如果是，直接放行
        //request.getURI().getPath() : 获取页面请求路径
        //.contains("/login/in")：是否包含/login/in
        if (request.getURI().getPath().contains("/login/in")){
            return chain.filter(exchange);
        }
        //3.获取当前用户的请求头jwt信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //4.判断当前令牌是否存在
        if (StringUtils.isEmpty(token)) {//如果token为空（null,""）,说明token不存在
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//不放行，拦截，并返回给页面信息
        }
        //5.如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken == 0 || verifyToken == -1) {
                //5.1 合法，则向header中重新设置userId
                String id = claims.getId();
                //重新设置用户的id到header中
                    //往请求头中设置数据，重新构建request对象
                    ServerHttpRequest.Builder aa = request.mutate().headers(new Consumer<HttpHeaders>() {
                        @Override
                        public void accept(HttpHeaders httpHeaders) {
                            httpHeaders.add("userId",id);
                        }
                    });
                    ServerHttpRequest serverHttpRequest = aa.build();
            //token过期了
            }else{
                //如果不存在，向客户端返回错误提示信息
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();//不放行，拦截，并返回给页面信息
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.放行
        return chain.filter(exchange);
    }

    /**
     * 优先级设置
     * 值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
